const dns2 = require('dns2');

const { Packet } = dns2;
let reqCount = 0;
const server = dns2.createServer({
    udp: true,
    handle: (request, send, rinfo) => {
        const response = Packet.createResponseFromRequest(request);
        const [question] = request.questions;
        
        console.log("rinfo___________",rinfo.address,rinfo.family,rinfo.port,rinfo.size);
        const { name } = question;
        const ip = ['127.0.0.5', '127.0.0.6', '127.0.0.7'];
        response.answers.push({
            name,
            type: Packet.TYPE.A,
            class: Packet.CLASS.IN,
            ttl: 300,
            address:'8.8.8.8'
        });
        // 模拟轮询
    console.log("request.questions[0].name",request.questions[0].name);
        if(request.questions[0].name === 'baidu.com' ){
            reqCount++;
            let mod = reqCount % 3;
            if (mod === 0) {
                response.answers[0].address = ip[0]
            } else if (mod === 1) {
                response.answers[0].address = ip[1]
            } else {
                response.answers[0].address = ip[2]
            }
        }
        send(response);
    }
});

server.on('request', (request, response, rinfo) => {
    console.log(request.header.id, request.questions[0]);
});
server.listen({
    udp: {
        port: 53,
        address: "127.0.0.9",
        type: "udp4",  // IPv4 or IPv6 (Must be either "udp4" or "udp6")
    },
});